package com.xaptul.docpreview.action;

import java.io.File;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.xaptul.docpreview.util.XaptulLog;

@RequestMapping("/upload")
@Controller
public class UploadController {

	private static final int MAX_UPLOAD_SIZE = 1024 * 1024 * 5; //5M

	private Logger log = XaptulLog.getLogger();
	
	private MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
	
	@RequestMapping(value = "/upload.html", method = RequestMethod.POST)
	public String uploadFile(@RequestParam MultipartFile file,
			HttpServletRequest request, Model model) {
		String documentStorePath = request.getSession().getServletContext()
				.getRealPath("tmp")
				+ File.separator;
		//使用 时间戳的原因是为了防止其它编码格式的文件名在系统中找不到，
		//例如文件名是汉字的话，在文件系统中找出来麻烦
		// 以后把文件保存在系统的时候 文件名 和 时间戳保存在数据库了，也方便搜索
		String docName = System.currentTimeMillis() + "."
				+ FilenameUtils.getExtension(file.getOriginalFilename());
		File f = new File(documentStorePath + docName);
		try {
			if (file.getSize() > MAX_UPLOAD_SIZE) {
				model.addAttribute("error","上传文件大小不能超过5M");// 文件大小要限制
			}else{
				file.transferTo(f);
				model.addAttribute("result",docName);
			}
		} catch (Exception e) {
			log.error("上传文件失败 ", e);
		}
		return "upload/uploadResult";
	}
}
